package per.destiny.seckill.service;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import per.destiny.seckill.constant.CommonConstants;
import per.destiny.seckill.exception.GlobalException;
import per.destiny.seckill.mapper.UserMapper;
import per.destiny.seckill.pojo.User;
import per.destiny.seckill.pojo.UserExample;
import per.destiny.seckill.util.CookieUtils;
import per.destiny.seckill.util.MD5Utils;
import per.destiny.seckill.util.UUIDUtils;
import per.destiny.seckill.vo.LoginVo;
import per.destiny.seckill.vo.RespBean;
import per.destiny.seckill.vo.RespBeanEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public List<User> getUserList() {
        return userMapper.selectByExample(null);
    }

    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        // 根据mobile查user，为什么不直接根据user和password查呢？因为password在数据库里做了二次加密，暂时获取不到salt
        User user = getUserByMobile(loginVo.getMobile());
        if (user == null) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断密码是否正确
        if (!MD5Utils.formPassToDBPass(loginVo.getPassword(), user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //生成cookie
        String ticket = UUIDUtils.uuid();
        // 将用户信息存入redis中
        redisTemplate.opsForValue().set("user:" + ticket, user);
//        request.getSession().setAttribute(ticket, user);
        CookieUtils.setCookie(request, response, CommonConstants.USER_TICKET, ticket);
        return RespBean.success();
    }

    private User getUserByMobile(String mobile) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andMobileEqualTo(mobile);
        List<User> users = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        } else {
            return users.get(0);
        }
    }

    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(userTicket)) {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if (user != null) {
            // 重新赋值一下cookie
            CookieUtils.setCookie(request, response, CommonConstants.USER_TICKET, userTicket);
        }
        return user;
    }
}
